package com.tuuzed.android.ui;

import android.content.Context;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class BottomTabGroup extends LinearLayout {
    private static final String TAG = "BottomTabGroup";
    private int mCheckedId = -1;
    private OnTabCheckedListener mOnTabCheckedListener;

    public BottomTabGroup(@NonNull Context context) {
        this(context, null);
    }

    public BottomTabGroup(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomTabGroup(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        super.addView(child, index, params);
        if (child instanceof BottomTabItem) {
            child.setOnClickListener(v -> checkedId(v.getId(), true));
        }
    }

    public void setOnTabCheckedListener(OnTabCheckedListener listener) {
        this.mOnTabCheckedListener = listener;
    }

    public void setCheckedId(@IdRes int checkedId) {
        checkedId(checkedId, false);
    }

    private void checkedId(@IdRes int checkedId, boolean isClick) {
        mCheckedId = checkedId;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = getChildAt(i);
            if (view instanceof BottomTabItem) {
                BottomTabItem item = (BottomTabItem) view;
                if (item.getId() == checkedId) {
                    item.checked(true);
                    if (mOnTabCheckedListener != null) {
                        mOnTabCheckedListener.onTabChecked(isClick, checkedId);
                    }
                } else {
                    item.checked(false);
                }
            }
        }
    }

    public boolean isCheckedId(@IdRes int checkedId) {
        return mCheckedId == checkedId;
    }

    public void enableBadge(@IdRes int itemId, boolean enable) {
        View item = findViewById(itemId);
        if (item != null && item instanceof BottomTabItem) {
            ((BottomTabItem) item).enableBadge(enable);
        }
    }

    public interface OnTabCheckedListener {
        void onTabChecked(boolean isClick, @IdRes int checkId);
    }
}
